//
//  AccountView.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/11/1.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

@objc protocol AccountViewDelegate {
    @objc optional func showTitleView(y:CGFloat) //显示标题
    @objc optional func addBillAction() //添加账单
    @objc optional func setBillAction(indexPath:IndexPath) //设置账单
    @objc optional func toReypayment(index:Int) //去还款
    @objc optional func showBillDetails(model:BillModel) //显示账单详情
}

class AccountView: UIView {
    
    weak var accountDelegate : AccountViewDelegate?
    
    var currentIndex = 0 //当前账单
    
    fileprivate let exampleCell = "exampleCell"
    fileprivate let accountCell = "accountCell"
    fileprivate let lifeBillCell = "lifeBillCell"
    
    var dataArray = [BillModel]() {
        didSet{
            self.tableView.reloadData()
        }
    }
    
    var headView : AccountHeadView!
    
    var tableView : UITableView!

    init() {
        super.init(frame: .zero)
    
        //账单数据解档
        if NSKeyedUnarchiver.unarchiveObject(withFile: cachesDir) != nil {
            
            self.dataArray = NSKeyedUnarchiver.unarchiveObject(withFile: cachesDir) as! [BillModel]
        }
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.mineColor()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ExampleCell.self, forCellReuseIdentifier: exampleCell)
        tableView.register(AccountCell.self, forCellReuseIdentifier: accountCell)
        self.addSubview(tableView)
        tableView.register(LifeBillCell.self, forCellReuseIdentifier: lifeBillCell)
        
        headView = AccountHeadView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 360)))
        tableView.tableHeaderView = headView
        
        let footView = AccountFootView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 110)))
        footView.addButton.addTarget(self, action: #selector(addBillAction), for: .touchUpInside)
        tableView.tableFooterView = footView
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
    }
    
    //MARK: 添加账单
    @objc fileprivate func addBillAction() {
        
        self.accountDelegate?.addBillAction!()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    //MARK: 选择账单操作
//    @objc fileprivate func selectOperateBill(sender:UILongPressGestureRecognizer) {
//        
//        if sender.state == .began {
//            
//            let location = sender.location(in: self.tableView)
//            let indexPath = self.tableView.indexPathForRow(at: location)
//            self.currentIndex = (indexPath?.row)!
//            self.accountDelegate?.setBillAction!(indexPath: indexPath!)
//        }
//    }
    
    //MARK: 删除账单
    @objc fileprivate func deleteBill(sender:UIButton) {
        
        self.dataArray.remove(at: sender.tag)
        self.tableView.reloadData()
        NSKeyedArchiver.archiveRootObject(self.dataArray, toFile: cachesDir) //账单数据归档
    }
    
    //MARK: 账单置顶
    @objc fileprivate func goTopForBill(sender:UIButton) {
        
        let model = self.dataArray[sender.tag]
        self.dataArray.remove(at: sender.tag)
        self.dataArray.insert(model, at: 0)
        self.tableView.reloadData()
        NSKeyedArchiver.archiveRootObject(self.dataArray, toFile: cachesDir) //账单数据归档
    }
    
    //MARK: 去还款
    @objc fileprivate func toRepayment(sender:UIButton) {
        
        self.accountDelegate?.toReypayment!(index: sender.tag)
    }
    
}

extension AccountView : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if dataArray.count == 0 {
            return 1
        }else{
            return dataArray.count
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 110)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if dataArray.count == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: exampleCell, for: indexPath) as? ExampleCell
            return cell!
        }else{
            
//            //长按手势
//            let longGesture = UILongPressGestureRecognizer.init(target: self, action: #selector(selectOperateBill(sender:)))
//            //长按时间
//            longGesture.minimumPressDuration = 1
            
            if dataArray[indexPath.row] is InputBillModel {
                let cell = tableView.dequeueReusableCell(withIdentifier: accountCell, for: indexPath) as? AccountCell
                cell?.selectionStyle = .none
                cell?.model = dataArray[indexPath.row] as? InputBillModel
                cell?.deleteButton.tag = indexPath.row
                cell?.topButton.tag = indexPath.row
                cell?.repaymentBtn.tag = indexPath.row
                cell?.deleteButton.addTarget(self, action: #selector(deleteBill(sender:)), for: .touchUpInside)
                cell?.topButton.addTarget(self, action: #selector(goTopForBill(sender:)), for: .touchUpInside)
                cell?.moreButton.layer.contents = UIImage.init(named: "more_select")?.cgImage
                cell?.repaymentBtn.addTarget(self, action: #selector(toRepayment(sender:)), for: .touchUpInside)
                cell?.deleteButton.isHidden = true
                cell?.topButton.isHidden = true
                cell?.isFlag = false
                
                if let model = dataArray[indexPath.row] as? InputBillModel {
                    if model.isPay == "1" {
                        cell?.repaymentBtn.isHidden = true
                    }else{
                        cell?.repaymentBtn.isHidden = false
                    }
                }
                
                return cell!
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: lifeBillCell, for: indexPath) as? LifeBillCell
                cell?.selectionStyle = .none
                cell?.model = dataArray[indexPath.row] as? LifeBillModel
                cell?.deleteButton.tag = indexPath.row
                cell?.topButton.tag = indexPath.row
                cell?.repaymentBtn.tag = indexPath.row
                cell?.deleteButton.addTarget(self, action: #selector(deleteBill(sender:)), for: .touchUpInside)
                cell?.topButton.addTarget(self, action: #selector(goTopForBill(sender:)), for: .touchUpInside)
                cell?.topButton.addTarget(self, action: #selector(goTopForBill(sender:)), for: .touchUpInside)
                cell?.moreButton.layer.contents = UIImage.init(named: "more_select")?.cgImage
                cell?.repaymentBtn.addTarget(self, action: #selector(toRepayment(sender:)), for: .touchUpInside)
                cell?.deleteButton.isHidden = true
                cell?.topButton.isHidden = true
                cell?.isFlag = false
                
                if let model = dataArray[indexPath.row] as? LifeBillModel {
                    if model.isPay == "1" {
                        cell?.repaymentBtn.isHidden = true
                    }
                }else{
                    cell?.repaymentBtn.isHidden = false
                }
                
                return cell!
            }
            
            
        }
        
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if dataArray.count == 0 {
            return
        }
        
        if let model = dataArray[indexPath.row] as? InputBillModel {
            self.accountDelegate?.showBillDetails!(model: model)
        }
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        self.accountDelegate?.showTitleView!(y: scrollView.contentOffset.y)
        
    }
    
    
}

